import { defineStore } from 'pinia';
import { DateTime } from 'luxon';

export const useProjectStore = defineStore('project', {
  state: () => ({
    projects: [],
    currentProject: null,
    isLoading: false
  }),

  actions: {
    loadProjects() {
      try {
        const projects = localStorage.getItem('projects');
        this.projects = projects ? JSON.parse(projects) : [];
      } catch (error) {
        console.error('Failed to load projects:', error);
        this.projects = [];
      }
    },
    async createProject(projectData) {
      const newProject = {
        ...projectData,
        id: crypto.randomUUID(),
        createdAt: DateTime.now().toISO(),
        updatedAt: DateTime.now().toISO(),
        metadata: {
          keySignature: 'C',
          timeSignature: '4/4',
          tempo: 120,
          ...projectData.metadata
        },
        content: {
          bars: [],
          lyrics: [],
          ...projectData.content
        }
      };
      this.projects.unshift(newProject);
      this.currentProject = newProject;
    },

    async updateProject(projectId, updates) {
      const index = this.projects.findIndex(p => p.id === projectId);
      if (index > -1) {
        this.projects[index] = {
          ...this.projects[index],
          ...updates,
          updatedAt: DateTime.now().toISO()
        };
        this.currentProject = this.projects[index];
      }
    },

    async deleteProject(projectId) {
      this.projects = this.projects.filter(p => p.id !== projectId);
      if (this.currentProject?.id === projectId) {
        this.currentProject = null;
      }
    },

    async importProject(file, formatType) {
      this.isLoading = true;
      try {
        const content = await this._parseFile(file, formatType);
        await this.createProject(content);
      } catch (error) {
        console.error('导入失败:', error);
        throw new Error(`文件导入失败: ${error.message}`);
      } finally {
        this.isLoading = false;
      }
    },

    async exportProject(projectId, formatType = 'json') {
      const project = this.projects.find(p => p.id === projectId);
      if (!project) throw new Error('项目不存在');

      const blob = await this._convertToFormat(project, formatType);
      this._downloadFile(blob, `${project.title}_${DateTime.now().toFormat('yyyy-LL-dd')}.${formatType}`);
    },

    async _parseFile(file, formatType) {
      const reader = new FileReader();
      
      return new Promise((resolve, reject) => {
        reader.onload = () => {
          try {
            let result;
            switch (formatType) {
              case 'json':
                result = JSON.parse(reader.result);
                break;
              case 'xml':
                result = this._parseXML(reader.result);
                break;
              case 'txt':
                result = this._parseText(reader.result);
                break;
              default:
                throw new Error('不支持的格式');
            }
            resolve(result);
          } catch (e) {
            reject(e);
          }
        };
        reader.readAsText(file);
      });
    },

    _convertToFormat(project, formatType) {
      let content, mimeType;
      switch (formatType) {
        case 'json':
          content = JSON.stringify(project, null, 2);
          mimeType = 'application/json';
          break;
        case 'xml':
          content = this._convertToXML(project);
          mimeType = 'application/xml';
          break;
        case 'txt':
          content = this._convertToText(project);
          mimeType = 'text/plain';
          break;
        default:
          throw new Error('不支持的导出格式');
      }
      return new Blob([content], { type: mimeType });
    },

    _downloadFile(blob, filename) {
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = filename;
      link.click();
      URL.revokeObjectURL(link.href);
    }
  },

  getters: {
    sortedProjects: (state) => [...state.projects].sort(
      (a, b) => DateTime.fromISO(b.updatedAt) - DateTime.fromISO(a.updatedAt)
    ),
    projectCount: (state) => state.projects.length,
    findProjectById: (state) => (id) => state.projects.find(p => p.id === id)
  }
});